package com.jichaoyun.sys.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.jichaoyun.model.vo.UserVo;
import com.jichaoyun.util.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

public class JWTInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
    Map<Object, Object> map = new HashMap<>();
    //如果是OPTIONS请求 直接放行
    String method = request.getMethod();
    try {
      if(method.equals("OPTIONS")){
        return  true;
      }
      //从请求中获取令牌
      String jwtToken = request.getHeader("token");
      if(jwtToken==null){
        throw new SignatureException("令牌不合法");
      }
      jwtToken = "Bearer " + jwtToken;
      //验证token
      UserVo user  = JwtUtil.verifyJwtToken(jwtToken);
      //验证成功后,如果令牌有效时间<=5分钟,则签发新的令牌,刷新令牌时间
      if(user != null){
        if(user.getExpireTimeVo() - System.currentTimeMillis() <= 1000L * 60 * 50){
          JwtUtil.refreshToken(user);
        }
        return  true ;
      }else{
        map.put("success",false);
        map.put("code",401);
        map.put("message","令牌已失效,请重新登录");
      }
    }catch(SignatureException e){
      e.printStackTrace();
      map.put("message","令牌不合法");
      map.put("code",401);
      map.put("success",false);
    }catch (Exception e) {
      e.printStackTrace();
      map.put("code",401);
      map.put("message","令牌已失效,请重新登录");
      map.put("success",false);
    }
    String jsonMap = new ObjectMapper().writeValueAsString(map);
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().println(jsonMap);
    return false;
  }

}
